package org.sgroup.imenu.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.sgroup.imenu.service.IMenuService;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;

public class DownloadMultiTask extends AsyncTask<List<String>, Integer, Void> {

	private  Context context;
	private  ProgressDialog prDiaLog;
	int len = 0;
	List<Bitmap> arrBitmap = new ArrayList<Bitmap>();
	IMenuService iService = new IMenuService();

	public DownloadMultiTask(Context _ctx, ProgressDialog _prog) {
		this.context = _ctx;
		this.prDiaLog = _prog;
	}

	@Override
	protected Void doInBackground(List<String>... params) {
		len = params[0].size();
		//for (String _url : params[0]) {
			 for(int i=0 ;i<len;i++){
				 String.valueOf(params);
			String name, path;
			String param = params[0].get(i);
			int index = param.lastIndexOf("/");
			if (index == -1) {
				name = param;
				path = "";
			} else {
				name = param.substring(index + 1);
				path = param.substring(0, param.lastIndexOf("/"));
			}
			String[] url = new String[3];
			url[0] = path;
			url[1] = name;
			if (name.lastIndexOf(".") == -1)
				return null;
			url[2] = GetURL(param);
			Bitmap bm = downloadImage(url[2]);
			if (bm != null)
				new CData(context).saveToInternalSorage(bm, name, path);
			arrBitmap.add(bm);
			// new DownloadTask(this.context).execute(url);
		}

		return null;
	}

	private String GetURL(String _name) {
		try {
			String result = this.iService.getImage(_name);
			String[] lines = result.split("\n");
			if (lines.length <= 1)
				return null;
			return lines[1];
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	protected void onProgressUpdate(Integer... values) {

		this.prDiaLog.setProgress(values[0]);
		if (arrBitmap != null) {
			this.prDiaLog.setMessage("Loading " + (arrBitmap.size() + 1) + "/"
					+ len);
		}
	}

	@Override
	protected void onPostExecute(Void result) {
		// super.onPostExecute(result);
		// if (isCancelled()) {
		// result = null;
		// }
	this.prDiaLog.dismiss();
	}

	private Bitmap downloadImage(String urlString) {
		urlString = urlString.replaceAll(" ", "%20");
		int count = 0;
		Bitmap bitmap = null;

		URL oUrl;
		InputStream inputStream = null;
		BufferedOutputStream outputStream = null;

		try {
			oUrl = new URL(urlString);
			URLConnection connection = oUrl.openConnection();
			int lenghtOfFile = connection.getContentLength();

			inputStream = new BufferedInputStream(oUrl.openStream());
			ByteArrayOutputStream dataStream = new ByteArrayOutputStream();

			outputStream = new BufferedOutputStream(dataStream);

			byte data[] = new byte[512];
			long total = 0;

			while ((count = inputStream.read(data)) != -1) {
				total += count;
				// publishing progress update on UI thread. Invokes
				 // onProgressUpdate();
			
				publishProgress((int) ((total * 100) / lenghtOfFile));

				// writing data to byte array stream
				outputStream.write(data, 0, count);
			}
			outputStream.flush();

			BitmapFactory.Options bmOptions = new BitmapFactory.Options();
			bmOptions.inSampleSize = 1;

			byte[] bytes = dataStream.toByteArray();
			bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length,
					bmOptions);

		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				inputStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				outputStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return bitmap;
	}

	@Override
	protected void onPreExecute() {
		//this.prDiaLog.setProgress(0);
	}

}
